package com.xxjqr.rbac.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.compression.DefaultCompressionCodecResolver;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Autoor:丁昌江
 * @Date:2021/4/4
 * @Description：
 */
@Data
@Slf4j
@ConfigurationProperties(prefix = "jwt")
@Component
public class JwtTokenUtil implements Serializable {

    /**
     * @描述 用户名的key
     */
    private static final String CLAIM_KEY_USERNAME = "sub";
    /**
     * @描述 创建时间的key
     */
    private static final String CLAIM_KEY_CREATED = "created";

    private String secret;

    private Long expiration;

    /**
     * @描述 token请求头名称
     */
    private String header;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static CompressionCodecResolver codecResolver = new DefaultCompressionCodecResolver();

    private String generateToken(Map<String, Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationTime())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 根据当前时间戳生成过期时间
     * @返回
     */
    private Date generateExpirationTime(){
        //*1000则表示将秒转为毫秒
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 根据token获取负载信息
     * @param token
     * @返回
     */
    private Claims getClaimsFromToken(String token){
        Claims claims = null;
        try{
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            log.error("Jwt格式验证失败: {}", token);
        }
        return claims;
    }

    /**
     * 从token中获取登录用户名
     * @param token
     * @返回
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username =  claims.getSubject();
        } catch (Exception e) {
            log.error("【JwtUtil】获取Claims中的用户名失败");
            username = null;
        }
        return username;
    }


    /**
     * 验证token是否还有效
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return userDetails!=null && username.equals(userDetails.getUsername()) && isTokenExpired(token);
    }

    /**
     * 判断token是否已经过期
     * @param token
     * @返回
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return !new Date().after(expiredDate);
    }


    /**
     * 从token中获取过期时间
     * @param token
     * @返回
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 根据用户信息生成token
     * @param userDetails
     * @返回
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>(2);
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    /**
     * 判断token是否可以被刷新
     * @param token
     * @返回
     */
    public boolean canRefresh(String token) {
        return isTokenExpired(token);
    }

    /**
     * 刷新token
     */
    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    public void setTokenExpiration(String token) {
        Claims claims = getClaimsFromToken(token);
        if (claims == null) {
            return;
        }
        claims.setExpiration(new Date());
    }
}
